//
//  HMStatusListViewModel.swift
//  SHWeibo01
//
//  Created by 卫平玉 on 16/7/23.
//  Copyright © 2016年 卫平玉. All rights reserved.
//

import UIKit

class SHStatusListViewModel: NSObject {

    lazy var statusList:[SHStatusViewModel] = [SHStatusViewModel]()
}

extension SHStatusListViewModel {
    
    func loadHomeData(isPullUp: Bool,isFinish:(isSuccess: Bool,count: Int)->()){
        /*
        - 如果是上啦记载更多  需要给服务器maxid   sinceid == 0
        - 如果是下拉刷新  需要给服务器sinceId   maxId == 0
        - 如果sinceid == 0  maxid == 0  默认服务器返回最新的20条数据
        */
        
        var sinceId: Int64 = 0
        
        var maxId: Int64 = 0
        
        if isPullUp{
            maxId = statusList.last?.status?.id ?? 0
            
            if maxId > 0{
                maxId -= 1
            }else{
                
                sinceId = statusList.first?.status?.id ?? 0
            }
        }
        
        SHNetworkTools.sharedTools.homeLoadData(sinceId, maxId: maxId, success: { (response) -> () in
            guard let res = response?["statuses"] as? [[String: AnyObject]] else{
                isFinish(isSuccess: false, count: 0)
                return
            }
            var tempArr: [SHStatusViewModel] = [SHStatusViewModel]()
            
            for dict in res{
                
                let status = SHStatus(dict: dict)
                
                let statusViewModel = SHStatusViewModel(status: status)
                tempArr.append(statusViewModel)
            }
            // 上拉加载更多
            if isPullUp {
                self.statusList = self.statusList + tempArr
                
                isFinish(isSuccess: true, count: -1)
            }else {
                // 下拉刷新
                self.statusList = tempArr + self.statusList
                 isFinish(isSuccess: true, count: tempArr.count)
            }
            
//            self.statusList = tempArr
            }) { (error) -> () in
                isFinish(isSuccess: false, count: 0)
                print("请求失败\(error)")
        }
        
    }
}
